import os
import sys
import re
import shutil
import commands
import _mysql
import logger
import metrics

# Find and insert commits to database
def analyze_scmlog(project, url, vcsinfo, db):
	logger.printinfo("Getting changelog from vcs")

	if os.path.exists ('/tmp/x90analy'):		
		shutil.rmtree("/tmp/x90analy")

	# Checkout first version first to collect activity data.
	logger.printinfo("Cloning latest version of repo, to get changeset ")

	# prepare cmd
	cmd = vcsinfo.changelog.replace("@[url]", url);
	cmd = cmd.replace("@[workdir]", "/tmp/x90analy");

	phand = os.popen(cmd)

	# read and parse output from the command
	while 1:
		line = phand.readline()
		if line == "": break

		# Match with regex.
		m = re.search(vcsinfo.regex, line)
		if m is not None:
			rev = m.group("REV")
			user = m.group("AUTHOR")
			date = m.group("YEAR")+"-"+m.group("MONTH")+"-"+m.group("DAY")
			db.insertscmlog(project.name, url, rev, user, date)

	phand.close()

# Analyze code of revisions (the last one each month)
def analyze_revisions(project, url, vcsinfo, db):
	logger.printinfo("Analyzing code")
	revisions = db.fetchrevisonstoanalyze(project.name, url)

	for revision in revisions: 
	       	logger.printinfo("\t[+] Checking out rev: "+revision)

		# prepare cmd
		cmd = vcsinfo.checkout.replace("@[rev]", revision);
		cmd = cmd.replace("@[workdir]", "/tmp/x90analy");

		# check it out!
		phand = os.popen(cmd)
		while 1:
			line = phand.readline()
			if line == "": break
		phand.close()

		metrics.analyze_metrics(project.name, revision, url, db, "/tmp/x90analy")


def analyze_project(project, vcsinfo, db):
	logger.printinfo("Analyzing:"+project.name);

	# Add project to database.
	db.insertproject(project.name, project.type);

	for url in project.urls:
		# Get revisions:
		analyze_scmlog(project, url, vcsinfo, db);

		# Analyze revisions:
		analyze_revisions(project, url, vcsinfo, db);
